import 'package:flutter/cupertino.dart';
import 'package:safetymonitor/app/components/common/no_permissions_widget.dart';
import 'package:safetymonitor/app/components/custom_modele/custom_cardx.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/app/data/entities/application/day_info_list_entity.dart';
import 'package:safetymonitor/generated/assets.dart';
import 'package:safetymonitor/modules/home/home_page/duty_manager/duty/controller.dart';
import 'package:safetymonitor/router/app_pages.dart';
import 'package:table_calendar/table_calendar.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:url_launcher/url_launcher_string.dart';

///值班管理
class DutyMgmtPage extends StatelessWidget {
  DutyMgmtPage({super.key});

  final controller = Get.put(DutyMgmtPageController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
        init: controller,
        builder: (_) {
          if (!controller.isNotPermissions) {
            return const NoPermissionsWidget(boolTOP:false);
          }
          return Scaffold(
            backgroundColor: const Color(0xffF7FBFE),
            body: _buildBody(),
          );
        });
  }

  Widget _buildBody() {
    return ListView(
      physics: const ClampingScrollPhysics(),
      padding: EdgeInsets.all(13.w),
      children: [
        _buildCalendar(),
        AppGaps.vGap10,
        GetBuilder(
            id: '_buildBody',
            init: controller,
            builder: (_) {
              return controller.selsectOneDaylist.planInfo!.isNotEmpty
                  ? _buildListView()
                  : Container(
                      color: Colors.white,
                      child: Column(
                        children: [
                          AppGaps.vGap36,
                          SvgPicture.asset('assets/svg/zhiban_empty_bg.svg'),
                          Text(
                            '暂无内容',
                            style: TextStyle(
                              color: const Color(0xFFC7CEE5),
                              fontSize: 14.sp,
                            ),
                          ),
                          AppGaps.vGap40,
                        ],
                      ),
                    );
            }),
      ],
    );
  }

  Widget _card(String title, Widget content, DayInfoListPlanInfo data) {
    return CustomCardX(
      padding: EdgeInsets.all(16.w),
      titleWidget: Row(
        children: [
          SvgPicture.asset(Assets.svgIconBlueStar, height: 13.w, width: 13.w),
          AppGaps.hGap10,
          Expanded(
            child: Text(
              title,
              style: TextStyle(
                fontSize: 16.w,
                color: const Color(0xff1D3452),
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          // Visibility(
          //   visible: controller.isFutureOrTodayDate(controller.selectedDate.value),
          //   child: Container(
          //     padding: EdgeInsets.only(
          //       left: 8.w,
          //       right: 8.w,
          //       top: 3,
          //       bottom: 3.w,
          //     ),
          //     decoration: BoxDecoration(
          //       color: Colors.blue,
          //       borderRadius: BorderRadius.all(
          //         Radius.circular(6.r),
          //       ),
          //     ),
          //     child: const Text(
          //       '交接班',
          //       style: TextStyle(color: Colors.white),
          //     ),
          //   ).clickOnce(() {
          //     //开始交接班
          //     Get.toNamed(Routes.startTheShift,arguments: data)?.then((_) {
          //       //刷新数据
          //     });
          //   }),
          // ),
        ],
      ),
      divider: CustomCardX.builtinDividerWithPadding,
      child: content,
    );
  }

  Widget _buildCalendar() {
    final now = DateTime.now();
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(13.w),
      ),
      child: Obx(() {
        return Column(
          children: [
            TableCalendar(
              firstDay: now.subtract(const Duration(days: 365)),
              lastDay: now.add(const Duration(days: 365)),
              headerStyle: const HeaderStyle(
                formatButtonVisible: false,
                titleCentered: true,
              ),
              focusedDay: controller.selectedDate.value,
              calendarFormat: controller.calendarFormat,
              //TableCalendar 的 daysOfWeekStyle 的 dowTextFormatter 属性允许你自定义星期文本的格式。
              daysOfWeekStyle: DaysOfWeekStyle(
                dowTextFormatter: (DateTime date, dynamic locale) {
                  // return  date.weekday.toString(); // 返回数字表示的星期
                  final int dayOfWeek = date.weekday;
                  if (dayOfWeek == 1) {
                    return '一';
                  } else if (dayOfWeek == 2) {
                    return '二';
                  } else if (dayOfWeek == 3) {
                    return '三';
                  } else if (dayOfWeek == 4) {
                    return '四';
                  } else if (dayOfWeek == 5) {
                    return '五';
                  } else if (dayOfWeek == 6) {
                    return '六';
                  } else if (dayOfWeek == 7) {
                    return '日';
                  }
                  return dayOfWeek.toString();
                },
                weekdayStyle: TextStyle(
                    fontSize: 14.sp, color: const Color(0xFF1D3452)),
                weekendStyle: TextStyle(
                    fontSize: 14.sp, color: const Color(0xFF1D3452)),
              ),
              onPageChanged: _onPageChanged,
              // 使用自定义的事件指示器构建器
              calendarBuilders: CustomEventIndicatorBuilder(),
              eventLoader: _loadEventsForDay,
              locale: 'zh_CN',
              calendarStyle: CalendarStyle(
                selectedDecoration: BoxDecoration(
                  shape: BoxShape.rectangle,
                  borderRadius: BorderRadius.circular(8.w),
                  color: !controller.curry
                      ? const Color(0xFFDCE3FC)
                      : const Color(0xFF1847E3),
                ),
                selectedTextStyle: TextStyle(
                  fontWeight: FontWeight.w700,
                  color: !controller.curry
                      ? const Color(0xFF1847E3)
                      : const Color(0xFFFFFFFF),
                  fontSize: 16.sp,
                ),
                todayDecoration: BoxDecoration(
                  shape: BoxShape.rectangle,
                  borderRadius: BorderRadius.circular(8.w),
                  color: const Color(0xFFDCE3FC),
                ),
                outsideDecoration:
                    const BoxDecoration(shape: BoxShape.rectangle),
                disabledDecoration:
                    const BoxDecoration(shape: BoxShape.rectangle),
                //enabledDayPredicate
                //位于当前选定范围内的日期单元格的装饰。
                withinRangeDecoration:
                    const BoxDecoration(shape: BoxShape.rectangle),
                //与“weekendDay”列表匹配的日期单元格的装饰。
                weekendDecoration:
                    const BoxDecoration(shape: BoxShape.rectangle),
                //圆角-必要1
                defaultDecoration:
                    const BoxDecoration(shape: BoxShape.rectangle),
                //圆角-必要2
                todayTextStyle: TextStyle(
                  color: const Color(0xFF1847E3),
                  fontWeight: FontWeight.w700,
                  fontSize: 14.sp,
                ),
              ),
              onDaySelected: (selectedDay, focusedDay) {
                //isSameDay 是一个方便的方法，用于在处理日期时判断两个日期是否表示同一天。
                bool istr = false;
                for (int i = 0; i < controller.eventsList.length; i++) {
                  //只有有事件的日期才可点击
                  if (isSameDay(
                      controller.eventsList[i].date, selectedDay)) {
                    istr = true;
                  }
                }
                //只有有事件的日期才可点击
                if (istr) {
                  controller.curry = true;
                  controller.selectedDate.value = selectedDay;

                  ///显示选中日期的人员列表
                  controller.selectDayPB(selectedDay);
                }
              },
              selectedDayPredicate: (day) =>
                  isSameDay(controller.selectedDate.value, day),
              daysOfWeekHeight: 27.w,
              startingDayOfWeek: _getStartingDayOfWeek(),
            ),
            Padding(
              padding:
                  EdgeInsets.only(bottom: 10.w, right: 10.w, left: 10.w),
              child: SvgPicture.asset(
                controller.calendarFormat == CalendarFormat.month
                    ? 'assets/svg/table_calendar_up.svg'
                    : 'assets/svg/table_calendar_down.svg',
              ),
            ).clickOnce(() {
              controller.calendarFormat =
                  controller.calendarFormat == CalendarFormat.month
                      ? CalendarFormat.week
                      : CalendarFormat.month;
              controller.update();
            }),
          ],
        );
      }),
    );
  }

  /// 实时数据
  Widget _buildListView() {
    // final children = <Widget>[];
    // for (final duty in controller.selsectOneDaylist.planInfo!) {
    //   children.add(_buildRealTimeItem(duty));
    // }
    //
    // return Column(
    //   children: children,
    // );
    return ListView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: controller.selsectOneDaylist.planInfo!.length,
      itemBuilder: (_, idx) =>
          _buildRealTimeItem(controller.selsectOneDaylist.planInfo![idx],controller.selsectOneDaylist.dutyDate),
    );
  }

  Widget _buildRealTimeItem(DayInfoListPlanInfo data, String? dutyDate) {
    return _card(
      '人员单位：${data.companyName}',
      Column(
        children: [
          _textRow('班次名称：', '${data.scheduleName}'),
          // _textRow('值班日期：', DateTime.fromMillisecondsSinceEpoch(data.dutyEndDate ?? 0).toDateStr),
          _textRow('值班日期：', '$dutyDate'),
          _textRow('值班人员：',  '${data.dutyPerson}'),
          _textRow('值班人员电话：',  '${data.dutyPersonPhone}',isCall: true),
          _textRow('值班室电话：',  '${data.dutyRoomLandline}',isCall: true),
          _textRow('值班领导：',  '${data.dutyLeader}'),
          _textRow('值班领导电话：', '${data.dutyLeaderPhone}',isCall: true),
        ],
      ),
        data,
    );
  }

  /// isCall: 是否是拨打电话
  Widget _textRow(String title, String content,{bool isCall = false}) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 3.w),
      child: Row(
        children: [
          Text(
            title,
            style: TextStyle(
              color: const Color(0xffC7CEE5),
              fontSize: 13.w,
            ),
          ),
          Expanded(
            child: !isCall ? Text(
              content,
              style: TextStyle(
                color: const Color(0xff1D3452),
                fontSize: 13.w,
              ),
            ) : InkWell(child: Text(content,style: TextStyle(
              color: const Color(0xff0223f6),
            ),), onTap: () {
              launchUrlString('tel:$content');
            }),
          ),
        ],
      ),
    );
  }

  ///切换页面回调
  void _onPageChanged(DateTime currentDate) async {
    controller.curry = true;
    print('_onPageChanged${currentDate}');
    // 在切换页面后，重新加载当前月份的事件
    controller.eventsList = await _loadEventsForCurrentMonth(currentDate);
    // 当前是展开才可以
    if (controller.eventsList.isNotEmpty&& controller.calendarFormat != CalendarFormat.week) {
      //有事件 就使用第一个事件
      controller.selectedDate.value = controller.eventsList.first.date;
      controller.getDayInfoList();
    } else {
      //没事件 就currentDate
      controller.selectedDate.value = currentDate;
      controller.getDayInfoList(isUpDate: true);
    }
  }


  ///加载当前'月份'的事件
  Future<List<EventModel>> _loadEventsForCurrentMonth(DateTime month) async {
    controller.selectedDate.value=month;
    return controller.getMonthEvent();
  }

  // 获取开始星期，保持今日居中显示
  StartingDayOfWeek _getStartingDayOfWeek() {
    // 获取开始星期
    switch (DateTime.now().weekday) {
      case DateTime.monday:
        return StartingDayOfWeek.friday;
      case DateTime.tuesday:
        return StartingDayOfWeek.saturday;
      case DateTime.wednesday:
        return StartingDayOfWeek.sunday;
      case DateTime.thursday:
        return StartingDayOfWeek.monday;
      case DateTime.friday:
        return StartingDayOfWeek.tuesday;
      case DateTime.saturday:
        return StartingDayOfWeek.wednesday;
      case DateTime.sunday:
        return StartingDayOfWeek.thursday;
      default:
        return StartingDayOfWeek.monday;
    }
  }

  /// 加载指定日期的事件
  List<EventModel> _loadEventsForDay(DateTime date) {
    print('datedate${date.toString()}');
    return controller.eventsList
        .where((event) =>
            event.date.year == date.year &&
            event.date.month == date.month &&
            event.date.day == date.day)
        .toList();
  }
}

/// 自定义事件指示器
class CustomEventIndicatorBuilder extends CalendarBuilders {
  CustomEventIndicatorBuilder()
      : super(
          markerBuilder: (context, date, events) {
            print('context, date, events---$date---$events');
            return events.isNotEmpty
                ? Transform.translate(
                    offset: const Offset(0, 15), // 偏移15像素到下方
                    child: Container(
                      width: 5,
                      decoration: const BoxDecoration(
                        shape: BoxShape.circle,
                        color: Color(0xFF0EB273),
                        //当前事件 设置color(是今天就设置0xFF1847E3)
                        // color: isSameDay(date, DateTime.now()) ?const Color(0xFF1847E3):const Color(0xFF0EB273),
                      ),
                    ),
                  )
                : Container(
                    margin: EdgeInsets.all(5.w),
                    decoration: BoxDecoration(
                      shape: BoxShape.rectangle,
                      //当前事件排除设置color(是今天就设置透明)
                      color: isSameDay(date, DateTime.now())
                          ? Colors.transparent
                          : const Color(0xFFF6F8FF).withOpacity(0.5),
                      borderRadius: BorderRadius.all(
                        Radius.circular(8.w),
                      ),
                    ),
                  );
          },
        );
}

/// 事件模型
class EventModel {
  EventModel({required this.title, required this.date});

  final String title;
  final DateTime date;
}
